package com.irdstudio.bsp.executor.core.plugin.migrate;

import com.irdstudio.bsp.executor.core.plugin.migrate.dao.MigrateIndexResultDao;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.irdstudio.bsp.executor.core.plugin.migrate.dao.MigrateCheckIndex;
import com.irdstudio.bsp.executor.core.plugin.migrate.dao.MigrationtabledataUtilDao;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

/**
 * <p>migrateCheckRuleUtil:迁移校验指标插件<p>
 * @author cjw
 * @date 2020-11-05
 */
public class migrateCheckIndexUtil {


	private static Logger logger = LoggerFactory.getLogger(migrateCheckIndexUtil.class);
	/**
	 * 表数据移指标插件实现方法
	 * params：migrateCheckIndexList迁移指标配置[]
	 */
	public boolean migrateCheckIndexrz(List<MigrateCheckIndex> migrateCheckIndexList, Connection conn){
		boolean result=true;
		try {
			//循环拿到的检查规则数据对迁移指标结果插入到迁移指标结果表中
			for (int i = 0; i < migrateCheckIndexList.size(); i++) {
				MigrateCheckIndex index=migrateCheckIndexList.get(i);
				MigrationtabledataUtilDao utildao=new MigrationtabledataUtilDao(conn);
				MigrateIndexResultDao migrateIndexResultDao = new MigrateIndexResultDao(conn);
				//通过配置的源表指标sql进行查询数据
				List<Map> sourceIndexlist = utildao.selecttablelist(index.getSourceIndexSql());
				//通过配置的目标指标sql进行查询数据
				List<Map> targetIndexlist = utildao.selecttablelist(index.getTargetIndexSql());
				Map sourcemap=sourceIndexlist.get(0);
				//源表指标统计值
				int sourcenum=0;
				for(Object key : sourcemap.keySet()){
					sourcenum =MapUtils.getInteger(sourcemap,key);
					break;
				}
				Map targetmap=targetIndexlist.get(0);
				//目标标指标统计值
				int targetnum=0;
				for(Object key : targetmap.keySet()){
					targetnum =MapUtils.getInteger(targetmap,key);
					break;
				}
				String check_expect_flag="";
				if(targetnum<=sourcenum){
					check_expect_flag="Y";
				}else{
					check_expect_flag="N";

				}
				boolean deltb= migrateIndexResultDao.deleteSql(index);
				if(!deltb){
					return  false;
				}
				//插入指标校验结果sql
				boolean insertTable = migrateIndexResultDao.addOrUpdateOrDeleteTable(index,sourcenum,targetnum,check_expect_flag);
				if(!insertTable){
					return false;
				}
				//数据治理任务处理
				if(check_expect_flag.equals("N")) {
					//先通过检查规则id查询是否已经生成了一条
					List<Map> governList = migrateIndexResultDao.selectTableList(index);
					if (governList.size() == 0) {
						boolean addSucceed = migrateIndexResultDao.addGovernSql(index);
						if (!addSucceed) {
							return false;
						}
					}
				}
			}
			return result;
		} catch (Exception e) {
			result = false;
			logger.error("检查规则出错！", e);
		}
		return  result;
	}
}
